"""
排行榜
"""
import datetime

from django.db import transaction

from src.utils import record
from common.models import TbMiniappUser, TbLeaderboard, TbLikeRecord


class LeaderboardDirector:
    def __init__(self):
        self.lr = record.LeaderBoardRecord()
        self.likerr = record.LikeRecordRoecord()

    def get_leaderboard(self, **kwargs):
        type = kwargs.get("type")
        type = str(type)
        if type == '3':
            return self.lr.filter_record()
        else:
            return self.lr.filter_record_order_by_filds("rank", type=type)

    def get_self_leaderboard(self, **kwargs):
        """
        获取个人排行榜
        """
        user: TbMiniappUser = kwargs.get("user")
        record = self.lr.get_record_condition(user_id=user.uid)
        return self.lr.record_obj_serializer(record)

    def get_record_detail(self, **kwargs):
        """
        获取记录详情
        """
        record_id = kwargs.get("record_id")
        return self.lr.get_record_detail(record_id)

    def like(self, **kwargs):
        """
        点赞
        """
        user: TbMiniappUser = kwargs.get("user")
        leaderboard_id = kwargs.get("leaderboard_id")
        method = kwargs.get("method")
        # 验证
        # --- start ---
        # like_record: TbLikeRecord = self.likerr.filter_record_obj(create_user_id=user.uid,
        #                                                           leaderboard_id=leaderboard_id,
        #                                                           is_delete=0).first()
        # if like_record is not None:
        #     if like_record.method == method:
        #         raise ValueError("")
        # --- end ---
        leaderboard: TbLeaderboard = self.lr.get_record(leaderboard_id)
        with transaction.atomic():
            if method == 1:
                leaderboard.like += 1
            else:
                if leaderboard.like > 0:
                    leaderboard.like -= 1
            leaderboard.save()
            like_record_info = {
                "create_user_id": user.uid,
                "create_user": user.username,
                "create_time": datetime.datetime.now(),
                "leaderboard_id": leaderboard_id,
                "method": method
            }
            self.likerr.create_record(**like_record_info)
            return self.lr.record_obj_serializer(leaderboard)

    def get_last_like_record(self, **kwargs):
        """
        获取最近一次点赞记录
        """
        user: TbMiniappUser = kwargs.get("user")
        leaderboard_id = kwargs.get("leaderboard_id")
        like_record: TbLikeRecord = self.likerr.filter_record_obj(create_user_id=user.uid,
                                                                  leaderboard_id=leaderboard_id,
                                                                  is_delete=0).first()
        return self.likerr.record_obj_serializer(like_record)
